import json

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django_redis import get_redis_connection
from pymysql import DatabaseError

from apps.news.models import News, Collection, Comment, Category
from apps.user.models import User
from libs.qiniuyun.uploadpic import storage


class DetailView(View):
    """详情页"""

    def get(self, request):
        u = request.GET.get('u')

        user = request.user
        new = News.objects.all().order_by("-comment_num")[:10]
        commit = Comment.objects.filter(news=u)
        commits = []
        for i in commit:
            if 'img[[' in i.content:
                commits.append({
                    "like_num": i.like_num,
                    'id': i.id,
                    'to_user': i.to_user,
                    'belong_user': i.belong_user,
                    'news': i.news,
                    'create_time': i.create_time,
                    'content': ' %s<img src="%s" width=100px height=100px>%s' % (
                        i.content[:i.content.find("img")], i.content[
                                                           i.content.find("img[[") + 5:i.content.find(
                                                               "]]")],
                        i.content[i.content.find("]]") + 2:]),

                })
            elif "a(" in i.content:
                commits.append({
                    "like_num": i.like_num,
                    'id': i.id,
                    'to_user': i.to_user,
                    'belong_user': i.belong_user,
                    'news': i.news,
                    'create_time': i.create_time,
                    'content': ' %s<a href="%s" target="_blank">%s</a>' % (
                        i.content[i.content.find("a((") - 1], i.content[
                                                              i.content.find("a((") + 3:i.content.find(
                                                                  "))")], i.content[
                                                                          i.content.find("a((") + 3:i.content.find(
                                                                              "))")])
                })
            else:
                commits.append(i)

        print(commit)
        try:
            news = News.objects.get(id=u)

        except News.DoesNotExist:
            response = redirect(reverse('index:index'))
            return response
        try:
            print(news.click_nums)
            news.click_nums = news.click_nums + 1
            print(news.click_nums)
            news.save()
        except News.DoesNotExist:
            response = redirect(reverse('index:index'))
            return response
        try:
            collections = Collection.objects.get(news=u, user=user.id, is_deleted=False)
            collection = "0"  # 0代表收藏
        except Collection.DoesNotExist:
            collection = "1"  # 1代表没有收藏
        # print(collections)

        print(news.title)
        print(collection, "*" * 10)
        if str(user) == "AnonymousUser":
            context = {
                "comment": commits,
                'new': new,
                "news": news,
                'user': user,
                'collection': collection
            }
        else:
            context = {
                "comment": commits,
                'new': new,
                "news": news,
                'user': user,
                'collection': collection
            }
        return render(request, 'jie/detail.html', context=context)


@method_decorator(csrf_exempt, name="dispatch")
class CollectView(LoginRequiredMixin, View):
    """收藏功能"""

    def post(self, request):
        # zl: "do"
        # news_id: 1261
        data = json.loads(request.body.decode("utf-8"))
        z = data.get("zl")
        print(z)
        news_id = data.get("news_id")
        user = request.user
        users = user.id
        print(type(users))
        if z == "do":
            try:
                try:
                    user = Collection.objects.get(user=users, news=news_id)
                    user.is_deleted = False
                    user.save()
                except Collection.DoesNotExist:
                    user = Collection.objects.create(user=users, news=news_id, is_deleted=False)
            except DatabaseError:
                return render(request, 'jie/detail.html', {'register_errmsg': '收藏失败'})
            ret = {
                "errno": 0,
                "errmsg": "收藏成功"
            }
            return http.HttpResponse(json.dumps(ret), content_type="application/json")
        elif z == "undo":
            """取消收藏"""

            try:
                # 查询要删除的地址
                collection = Collection.objects.get(user=users, news=news_id, is_deleted=False)
                # 将地址逻辑删除设置为True
                collection.is_deleted = True
                collection.save()
            except Exception as e:
                return render(request, 'jie/detail.html', {'register_errmsg': '取消收藏失败'})
            ret = {
                "errno": 0,
                "errmsg": "收藏成功"
            }
            return http.HttpResponse(json.dumps(ret), content_type="application/json")


@method_decorator(csrf_exempt, name="dispatch")
class ReplyView(View):
    """评论"""

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        # content: "face[熊猫] "
        # reply_id: "None"
        # news_id: 1261
        user = request.user
        print(user.username, "*")
        if user.username == "":
            ret = {"status": 8009, "msg": "缺少参数222"}
            return http.HttpResponse(json.dumps(ret), content_type="application/json")
        content = data.get("content")
        print(content)
        reply_id = data.get("reply_id")
        news_id = data.get("news_id")
        news = News.objects.get(id=news_id)

        print(type(reply_id))
        if not all([content, reply_id, news_id]):
            ret = {"status": 101, "msg": "缺少参数"}
            return http.HttpResponse(json.dumps(ret), content_type="application/json")
        try:
            if reply_id != "None":
                to_user = Comment.objects.get(id=reply_id)
                user = Comment.objects.create(belong_user=request.user, news=news, content=content, to_user=to_user)
            else:
                user = Comment.objects.create(belong_user=request.user, news=news, content=content)
            try:
                user = Comment.objects.filter(news_id=news_id)
                num = len(user)
                news.comment_num = num
                news.save()
            except News.DoesNotExist:
                response = redirect(reverse('news:detail'))
                return response
        except Comment.DoesNotExist:
            response = redirect(reverse('news:detail'))
            return response
        ret = {"status": 0, "msg": "评论成功"}
        return http.HttpResponse(json.dumps(ret), content_type="aqupplication/json")


@method_decorator(csrf_exempt, name="dispatch")
class ApiUploadView(LoginRequiredMixin, View):
    def post(self, request):
        avatar = request.FILES.get("file")
        print(avatar)
        image_data = avatar.read()
        print(type(image_data))
        file_name = storage(image_data)
        # 将七牛云返回的图片名字拼接成url存储到数据库
        new_image_url = "http://images.zyntt.cn" + "/" + file_name
        # try:
        #     user = request.user
        #     mobile = user.mobile
        #     users = User.objects.get(mobile=mobile)
        #     print(users.images_url)
        #     users.images_url = new_image_url
        #     users.save()
        # except Exception as e:
        #     return http.JsonResponse({'code': 100, 'errmsg': '设置地址标题失败'})
        ret = {"status": 0, "msg": new_image_url}
        return http.HttpResponse(json.dumps(ret), content_type="application/json")


@method_decorator(csrf_exempt, name="dispatch")
class LikeView(LoginRequiredMixin, View):
    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        new_id = data.get("id")
        try:
            comment = Comment.objects.get(id=new_id)
            comment.like_num = comment.like_num + 1
            comment.save()
        except Comment.DoesNotExist:
            response = redirect(reverse('news:detail'))
            return response
        ret = {"status": 0, "msg": "点赞成功"}
        return http.HttpResponse(json.dumps(ret), content_type="aqupplication/json")


@method_decorator(csrf_exempt, name="dispatch")
class AddView(LoginRequiredMixin, View):
    def get(self, request):
        user = request.user
        context = {
            'user': user,
        }
        return render(request, 'jie/add.html', context=context)

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        # 获取数据
        # type: "1"
        # title: "123456"
        # content: "123456"
        # reward: "10"
        # img_code: "MMAD"
        # uuid: "7c14a6e1-744d-461b-b8b5-cecfdb2c33a2"
        user = request.user
        type = data.get("type")
        title = data.get("title")
        content = data.get("content")
        reward = data.get("reward")
        img_code = data.get("img_code")
        uuid = data.get("uuid")
        if not all([content, type, title, reward, img_code, uuid]):
            ret = {"status": 101, "msg": "缺少参数"}
            return http.HttpResponse(json.dumps(ret), content_type="application/json")
        if "face[" in content:
            num_dict = {}
            num = content[content.find("face[") + 5:content.find("face[") + 7]
            print(num)
        if content:
            contentsss = "<div class='detail-body layui-text photos'>%s</div>" % (
                content)
        else:
            ret = {"status": 101, "msg": "缺少参数"}
            return http.HttpResponse(json.dumps(ret), content_type="application/json")
        print("------------contentss----------------")
        print(contentsss)
        print("------------contentsss----------------")
        redis_conn = get_redis_connection('code')
        t_f = redis_conn.get("img_%s" % uuid)
        if not t_f:
            return http.JsonResponse({'status': "7410", 'msg': '验证码错误'})
        if t_f.decode().lower() != img_code.lower():
            return http.JsonResponse({'status': "200", 'msg': '验证码错误'})
        try:
            category = Category.objects.get(id=type)
            news = News.objects.create(content=contentsss, award=reward, title=title, category=category, user=user)
        except News.DoesNotExist:
            ret = {"status": 103, "msg": "发布失败"}
            return http.HttpResponse(json.dumps(ret), content_type="application/json")
        ret = {"status": 0, "msg": "发布成功"}
        return http.HttpResponse(json.dumps(ret), content_type="application/json")
